"""
@author: sumeng
@file: 三乐购物系统-讲解.py
@time: 2023/4/14 10:04
"""
import pickle

class User:
    def __init__(self, name, passwd, init_amount):
        self.name = name
        self.passwd = passwd
        self.init_amount = init_amount
        self.shopping_car = {}


#shopping_system
class ShoppingSystem:
    def __init__(self, goods_info, sys_info):
        self.goods_info = goods_info
        self.sys_info = sys_info
        self.userdict = {}

    def load_user(self):
        file_name = self.sys_info + "_user.pickle"
        try:
            with open(file_name, "rb") as fp:
                self.userdict = pickle.load(fp)
        except:
            # 忽略异常 不做任何事情
            pass

    def write_file(self):
        file_name = self.sys_info + "_user.pickle"
        with open(file_name, "wb") as fp:
            pickle.dump(self.userdict, fp)

    def register(self, name, passwd, initial_amount):
        if name not in self.userdict:
            # 创建一个新用户，实例化User类
            user = User(name, passwd, initial_amount)
            #把名字作为key，user对象作为value 存在self.userdict里面
            #{"sc":user对象}
            self.userdict[name] = user
        else:
            print("用户已存在")

    def login(self, name, passwd):
        if name in self.userdict and passwd == self.userdict[name].passwd:
            return True
        return False

    def check_message(self):
        print("商品编号".ljust(10, " "), "商品名字".ljust(8, " "), "商品价格")
        for i in self.goods_info:
            product_name = self.goods_info[i]["name"]
            product_price = self.goods_info[i]["price"]
            print(f"{i}".ljust(10, " "), f"{product_name}".ljust(10, " "), f"{product_price}")

    def add_goods(self, goods_id, goods_num, name):
        self.userdict[name].shopping_car[goods_id] = goods_num
        print(f"加购{goods_num}个{self.goods_info[goods_id]['name']}商品成功！")

    def pay_cart(self, name):
        cart = self.userdict[name].shopping_car
        if cart:
            money = int(self.userdict[name].init_amount)
            pay = 0
            for i in cart:
                pay += int(cart[i]) * self.goods_info[i]['price']
            if pay <= money:
                print(f"你一共需要支付{pay}元")
                self.userdict[name].init_amount = money - pay
                print(f"你的余额为{self.userdict[name].init_amount}")
                self.userdict[name].shopping_car.clear()
            else:
                print("你的余额不足！")
        else:
            print("购物车为空，无法结算！")

    def check_cart(self, name):
        cart = self.userdict[name].shopping_car
        if cart:
            print("以下为购物车中的商品信息".center(40, "*"))
            for i in cart:
                print(f"{self.goods_info[i]['name']}的编号为{i},单价为{self.goods_info[i]['price']},加购了{cart[i]}件")
        else:
            print("购物车为空！")


    def add_amount(self, name, money):
        self.userdict[name].init_amount = self.userdict[name].init_amount + int(money)
        print(f"充值成功！你的余额为{self.userdict[name].init_amount}")


fruit_goods = {
    'F0001': {"name": "苹果", "price": 8},
    'F0002': {"name": "香蕉", "price": 4}
}


medicine_goods = {
    'M0001': {"name": "奥司他韦", "price": 60},
    'M0002': {"name": "抗病毒口服液", "price": 30}
}
system1 = ShoppingSystem(fruit_goods, "水果购物系统")
system2 = ShoppingSystem(medicine_goods, "药品购物系统")

system = [system1, system2]

while 1:
    print("当前平台，已有购物系统如下：")
    for k, v in enumerate(system):
        print(f"{k}.{v.sys_info}")
    c1 = input("请输入你的选择(按q退出):")
    if c1 == "q":
        break
    if c1.isdigit() and int(c1) < len(system):
        c1 = int(c1)
        current_system = system[c1]
        current_system.load_user()
        print(f"欢迎进入{current_system.sys_info}".center(40, "*"))
        while 1:
            c2 = input("1.登录\n2.注册\n3.查看已有用户\n请输入你的选择(按q退出):")
            if c2 == "q":
                break
            if c2 == "1":
                name, passwd = input("请输入你的名字、密码(用空白分隔):").split()
                if current_system.login(name, passwd):
                    print(f"{name}用户登录成功！")
                    print(f"你的余额为{current_system.userdict[name].init_amount}")
                    while 1:
                        c3 = input("1、查看商品\n2、添加购物车\n3、查看购物车\n4、结算购物车\n5、充值\n请输入你的选择(按q退出):")
                        if c3 == "q":
                            break
                        elif c3 == "1":
                            print("*" * 20)
                            current_system.check_message()
                        elif c3 == "2":
                            print("*" * 20)
                            while 1:
                                goods_id = input("请输入你需要加购的编号：")
                                goods_num = input("请输入你想要加购的数量：")
                                if goods_id in current_system.goods_info:
                                   break
                                print("不存在该商品，请重新输入！")
                            current_system.add_goods(goods_id, goods_num, name)
                            current_system.write_file()
                        elif c3 == "3":
                            current_system.check_cart(name)
                        elif c3 == "4":
                            current_system.pay_cart(name)
                            current_system.write_file()
                        elif c3 == "5":
                            money = input("请输入你要充值的金额：")
                            current_system.add_amount(name, money)
                            current_system.write_file()
                        else:
                            print("输入错误，请重新输入！")
                else:
                    print("登录失败，请重新登录！")
            elif c2 == "2":
                name, passwd, amount = input("请输入你的名字、密码、初始金额（用空白分割）").split()
                current_system.register(name, passwd, amount)
                current_system.write_file()
            elif c2 == "3":
                print(f"当前系统用户有:{current_system.userdict}")
            else:
                print("输入有误！")
    else:
        print("输入有误，请重新输入！")